package com.ruoyi.oss.aliyun.listener;

import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * PutObject文件上传事件进度监听
 *
 * @author xueyu
 */
@Setter
@Getter
@Slf4j
public class PutObjectProgressListener implements ProgressListener {

    /**
     * 写人字节数
     */
    private long bytesWritten = 0;
    /**
     * 总数
     */
    private long totalBytes = -1;

    /**
     * 是否成功
     */
    private boolean succeed = false;

    /**
     * 进度事件回调
     *
     * @param progressEvent 事件
     */
    @Override
    public void progressChanged(ProgressEvent progressEvent) {
        long bytes = progressEvent.getBytes();
        ProgressEventType eventType = progressEvent.getEventType();
        switch (eventType) {
            case TRANSFER_STARTED_EVENT:
                log.info("开始上传......");
                break;
            case REQUEST_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                log.info("【{}】字节将上传到 OSS", this.totalBytes);
                break;
            case REQUEST_BYTE_TRANSFER_EVENT:
                this.bytesWritten += bytes;
                if (this.totalBytes != -1) {
                    int percent = (int) (this.bytesWritten * 100.0 / this.totalBytes);
                    log.info("此时已写入【{}】字节 ,上传进度: {}%({}/{})", bytes, percent, this.bytesWritten, this.totalBytes);
                } else {
                    log.info("此时已写入【{}】字节 , 上传比率: unknown({}/...)", bytes, this.bytesWritten);
                }
                break;
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                log.info("上传成功,【{}】字节已全部上传,状态:【{}】", this.bytesWritten, this.succeed);
                break;
            case TRANSFER_FAILED_EVENT:
                this.succeed = false;
                log.error("上传失败,【{}】bytes 已被转移,状态:【{}】", this.bytesWritten, this.succeed);
                break;
            default:
                break;
        }
    }
}
